/**
 * Created by YJH on 2018/5/30.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    Image,
    Button,
    AsyncStorage,
    Alert,
} from 'react-native';
import NavigationBarComponent from '../NavigationBarComponent';
import TabCustomPage from './TabCustomPage';
import ArrayUtil from '../../util/ArrayUtil';
import Toast, {DURATION} from 'react-native-easy-toast';
import LanguageDao, {FLAG_LAN} from '../../expand/dao/LanguageDao';
import NavigationBarUtil from '../../util/NavigationBarUtil';
import SortableListView from 'react-native-sortable-listview'

const KEY = 'KEY-Async';
export default class SortKeyPage extends Component {

    constructor(props) {
        super(props);

        this.languageDao = this.props.isPopular?new LanguageDao(FLAG_LAN.flagKey):new LanguageDao(FLAG_LAN.flagLanguage);
        this.dataArray = [];//原始数据存储
        this.sortResultArray = [];//重新排序之后，新生成的数组
        this.originalCheckedArray = [];//checked 原始数据数组

        this.state = {
            //已经定义的标签
            checkedArray: [],//checked 动态变化的数据数组
            theme:this.props.theme,
        }

    }

    componentDidMount() {
        this.languageDao.fetch()
            .then((result) => {
                this.getCheckedItems(result);
            }).catch(error => {
            console.log(error)
        })
    }

    getCheckedItems(result) {
        this.dataArray = result;
        let checkedArray = [];
        for (let i = 0, len = result.length; i < len; i++) {
            if (result[i].checked) {
                checkedArray.push(result[i]);
            }
        }

        this.setState({
            checkedArray: checkedArray,
        });

        this.originalCheckedArray = ArrayUtil.cloneArray(checkedArray);
    }

    loadDataFromSql() {

    }

    onSave(isBack) {
        let bol = ArrayUtil.isArrayEqual(this.state.checkedArray, this.originalCheckedArray)
        if (isBack) {//如果时点击了返回按钮
            if (!bol) {
                //标签顺序已经改变
                Alert.alert(
                    '提醒',
                    '标签顺序已修改，是否保存？',
                    [
                        // {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
                        {
                            text: '取消', onPress: () => {
                            this.props.navigator.pop();
                        }, style: 'cancel'
                        },
                        {
                            text: '保存', onPress: () => {
                            this.getSortKeyResult();
                            this.languageDao.save(this.sortResultArray);
                            this.props.navigator.pop();
                        }
                        },
                    ],
                    {cancelable: false}
                );

                return;
            }
            this.props.navigator.pop();


        } else {
            //如果时点击了保存按钮
            // let bol = ArrayUtil.isArrayEqual(this.state.checkedArray, this.originalCheckedArray);
            // this.toast.show('origin==' + this.originalCheckedArray[2].name);
            if (bol) {
                this.toast.show('标签顺序没有改变');
                this.props.navigator.pop();
                // this.toast.show('checked==' + this.state.checkedArray[0].name + "---" + this.sortResultArray[0].name);
                return;
            } else {
                //已经进行了排序
                this.toast.show('标签顺序已经改变');
                this.getSortKeyResult();
                this.languageDao.save(this.sortResultArray);
                this.props.navigator.pop();
                return;
            }


        }
    }

    getSortKeyResult() {
        this.sortResultArray = ArrayUtil.cloneArray(this.dataArray);
        for (let i = 0, len = this.originalCheckedArray.length; i < len; i++) {
            let item = this.originalCheckedArray[i];
            let index = this.dataArray.indexOf(item);
            this.sortResultArray.splice(index, 1, this.state.checkedArray[i])
        }
        // this.toast.show('checked==' + this.sortResultArray[0].name);
    }

    render() {
        return <View style={styles.container}>
            <NavigationBarComponent
                leftButton={NavigationBarUtil.getLeftButton(() => this.onSave(true))}
                rightButton={NavigationBarUtil.getRightButtonWord(() => this.onSave(false), '保存')}
                title={this.props.menuType}
                style={this.state.theme.styles.navBar}
                statusBar={{backgroundColor:this.state.theme.themeColor}}

            />
            {/*<SortableListView*/}
            {/*style={{flex: 1}}*/}
            {/*data={this.state.checkedArray}*/}
            {/*order={Object.keys(this.state.checkedArray)}*/}
            {/*onRowMoved={e => {*/}
            {/*order.splice(e.to, 0, this.state.checkedArray.splice(e.from, 1)[0]);*/}
            {/*this.forceUpdate()*/}
            {/*}}*/}
            {/*renderRow={row => <RowComponent data={row}/>}*/}
            {/*/>*/}
            <SortComponent array={this.state.checkedArray} {...this.props}/>

            <Toast ref={toast => this.toast = toast}/>
        </View>
    }
}

class SortComponent extends React.Component {

    render() {
        return (
            <SortableListView
                style={{flex: 1}}
                data={this.props.array}
                order={Object.keys(this.props.array)}
                onRowMoved={e => {
                    this.props.array.splice(e.to, 0, this.props.array.splice(e.from, 1)[0]);
                    this.forceUpdate()
                }}
                renderRow={row => <RowComponent arra={row} {...this.props}/>}
            />
        )
    }
}

class RowComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            theme:this.props.theme,
            array:this.props.arra,
        }

    }
    render() {
        return (
            <TouchableHighlight
                underlayColor={'#eee'}
                style={{
                    padding: 20,
                    backgroundColor: '#F8F8F8',
                    borderBottomWidth: 1,
                    borderColor: '#eee',
                }}
                {...this.props.sortHandlers}
            >
                <View style={{flexDirection: 'row'}}>

                    <Image style={{tintColor: this.state.theme.themeColor, width: 20, height: 20}}
                           source={require('../../../res/images/ic_sort.png')}/>
                    <Text style={{marginLeft: 15}}>{this.state.array.name}</Text>
                </View>
            </TouchableHighlight>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    text: {
        color: 'black',
        fontSize: 30,
        alignSelf: 'center',
    }
});